<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-16 09:53:28
 * @Last Modified time: 2023-02-21 16:24:57
 */
namespace app\common\services\store\order;

use app\common\dao\store\OrderDao;
use think\facade\Db;

use frank\base\BaseService;
use frank\exception\CommonException;

use app\common\enum\pay\PayTypeEnum;
use app\common\factory\store\goods\source\Factory as StockFactory;
use app\common\enum\store\order\SourceEnum;
use app\common\enum\user\WaterSourceEnum;
use app\common\services\user\UserWaterService;
use app\common\services\store\OrderDeliveryService;
use app\common\services\pay\RefundService;
/**
 * Class RefundSuccessService
 */
class RefundSuccessService extends BaseService
{
	// 订单
    public $detail;

    // 当前用户信息
    private $user;

    /**
     * PaySuccessService constructor.
     * @param OrderDao $dao
     */
    public function __construct(OrderDao $dao,$orderNo)
    {
        $this->dao = $dao;
        // 实例化订单模型
        $this->detail = $this->dao->search(['order_no'=>$orderNo])->with(['user_detail','goods'])->find();
        if (is_null($this->detail)) {
            throw new CommonException('订单不存在');
        } 
        // 获取用户信息
        $this->user = $this->detail['user_detail'];
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetail()
    {
        return $this->detail;
    }

      /**
     * 订单退款成功业务处理
     */
    public function onRefundSuccess($payType, $payData = [])
    {
        if (empty($this->detail)) {
            $this->error = '未找到该订单信息';
            return false;
        }
        Db::startTrans();
        try {
         	// 回退商品库存
            StockFactory::getFactory($this->detail['order_source']['value'])->backGoodsStock($this->detail['goods'], true);

            $userAccount = '';

            $water = [
                'pay_type'=>$payType,
                'soure_id' => $this->detail['order_id'],
                'user_id' => $this->user['id'],
                'money' => $payData['refund_price'],
            ];

            // 余额退款
            if ($payType == PayTypeEnum::WALLET) {
                // 更新用户余额
                $this->user->inc('balance', $payData['refund_price'])->update();
                $water['user_balance'] = $this->user->balance + $payData['refund_price'];
                $userAccount = '基本账户余额';
            }
            
            // 记录用户流水
            UserWaterService::instance()->createWater(WaterSourceEnum::ORDERREFUND,$water, ['order_no' => $this->detail['order_no']] );

            // 更新订单状态
            $this->detail->save([
            	'pay_refund'=>1
            ]);

            // 更新退款单状态
            RefundService::instance()->updateResult(
            	$this->detail['order_source']['value'],
            	$this->detail['id'],
            [
            	'refund_time'=>time(),
            	'success_time'=>time(),
            	'refund_status'=>1,
            	'payer_total'=>$this->detail['pay_price'],
            	'payer_refund'=>$this->detail['pay_price'],
            	'user_account'=>$userAccount,
            ]);
            // 提交事务
            Db::commit();
            return true;
        } catch (Exception $e) {
            $this->error = $e->getMessage() ?? '';
            // 回滚事务
            Db::rollback();
            return false;
        }
    }


}
